import 'package:eshi/app/shi/data/History.dart';
import 'package:eshi/app/shi/data/tabtxt_history.dart';
import 'package:eshi/app/shi/tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:eshi/app/GlobalHandler.dart';
import 'package:eshi/app/MyHomePage.dart';
import 'package:eshi/app/SettingsPage.dart';
import 'package:eshi/main.dart';
import 'package:eshi/NumInput.dart';
import 'package:eshi/app/settings/AppLocalizations.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:go_router/go_router.dart';


class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() => MyAppState();

  static of(BuildContext context) {
       final MyAppState? result = context.findRootAncestorStateOfType<MyAppState>();
      if (result != null) {
        return result;
      }
      throw FlutterError.fromParts(<DiagnosticsNode>[]);
  }

}
class MyAppState extends State<MyApp> {
  //语言 
  Locale? _locale = Config.languageLocale;
  set locale(v) => setState(() {
      _locale = v;
  });
   // 主题模式：默认跟随系统
  ThemeMode _themeMode = ThemeMode.system;
  set themeMode(v) => setState(() {
      _themeMode = v;
  }); 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'eshi',
      initialRoute: '/',
      routes: {
        '/': (context) => MyHomePage(title: 'simple history',key: mainWidgetKey),       // 首页
        '/settings': (context) => SettingsPage(), // 配置页
        '/numInput': (context) => NumInputWidget(), //数字输入
      },
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),

         brightness: Brightness.light,
        primarySwatch: Colors.blue,
        // backgroundColor: Colors.white,
        cardColor: Colors.grey[50],
        textTheme: const TextTheme(
          bodyLarge: TextStyle(color: Colors.black87),
          titleLarge: TextStyle(color: Colors.black),
        ),
      ),
       // 深色主题
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.blue,
        cardColor: Colors.grey[800],
        textTheme: const TextTheme(
          bodyLarge: TextStyle(color: Colors.white70),
          titleLarge: TextStyle(color: Colors.white),
        ),
      ),
        // 当前主题模式
      themeMode: _themeMode,
      locale: _locale,
      supportedLocales: Language.locales(),
      localizationsDelegates: const [
        AppLocalizations.delegate,
          // 2. 以下三个是官方必须的代理，缺一不可
        GlobalMaterialLocalizations.delegate,  // Material组件本地化
        GlobalWidgetsLocalizations.delegate,   // 全局Widget本地化
        GlobalCupertinoLocalizations.delegate, // Cupertino组件本地化
      ],
       // 全局包装器：为所有页面添加返回事件监听
      builder: (context, child) {
        return KeyboardEventListener(child:child);
        //return GlobalBackHandler(child: child!);
      },
      // home: MyHomePage(title: 'simple history',key: mainWidgetKey ),
    );
  }
}

// 路由配置
final GoRouter router = GoRouter(
  routes: <RouteBase>[
    GoRoute(
      path: '/',
      builder: (BuildContext context, GoRouterState state) {
        return MyHomePage(title: 'simple history',key: mainWidgetKey);
      },
    ),
    // 自定义产品路由 (支持 /product?id=123&name=xxx 格式)
    GoRoute(
      path: '/settings',
      builder: (BuildContext context, GoRouterState state) {
        return SettingsPage();
      },
    ),
    // 自定义产品路由 (支持 /product?id=123&name=xxx 格式)
    GoRoute(
      path: '/numInput',
      builder: (BuildContext context, GoRouterState state) {
        return NumInputWidget();
      },
    ),
    // 自定义用户路由 (支持 /user/123 格式)
    GoRoute(
      path: '/path/:path',
      builder: (BuildContext context, GoRouterState state) {
        var path = state.pathParameters['path']!;
        var p = path.split(".");
        return MyHomePage(title: 'simple history',key: mainWidgetKey,path:p);
      },
    ),
  ],
  // 处理未匹配的路由
  errorBuilder: (context, state) {
    return Scaffold(
      appBar: AppBar(title: const Text('页面不存在')),
      body: Center(child: Text('无法识别的URL: ${state.uri}')),
    );
  },
);